package jlfm.lastfm.apps;

import java.io.InputStream;

import jlfm.lastfm.client.TrackMetadata;
import jlfm.lastfm.client.events.LastFmClientListener;
import jlfm.lastfm.client.impl.simple.SimpleLastFmClient;
import jlfm.lastfm.client.impl.simple.StreamHandler;
import jlfm.lastfm.station.LastFmStation;

abstract public class AbstractStreamHandler implements StreamHandler {
	private SimpleLastFmClient client;

	private StreamHandlerThread handlerThread;

	private boolean end = false;

	public synchronized boolean isEnd() {
		return end;
	}

	public synchronized void setEnd(boolean end) {
		this.end = end;
	}

	public AbstractStreamHandler(SimpleLastFmClient clientToObserve) {
		setClient(clientToObserve);
	}

	public void setClient(SimpleLastFmClient clientToObserve) {
		/* remove old client */
		if (this.client != null) {
			this.client.removeClientListener(handlerThread);
		}

		handlerThread = new StreamHandlerThread(clientToObserve, this);

		/* add new cient */
		this.client = clientToObserve;
		clientToObserve.addClientListener(handlerThread);

	}

	private class StreamHandlerThread extends Thread implements
			LastFmClientListener {

		private SimpleLastFmClient client;

		private StreamHandler streamHandler;

		public StreamHandlerThread(SimpleLastFmClient client,
				StreamHandler streamHandler) {
			this.client = client;
			this.streamHandler = streamHandler;
		}

		public void tunedIn(LastFmStation station) {
			start();
		}

		@Override
		public void run() {
			while (!isEnd()) {
				InputStream in = client.getStream();
				TrackMetadata m = client.getTrackInfo();
				streamHandler.handleStream(m, in);
			}
		}

		// ////////////////////
		public void loggedIn(String user, String session) {
		}
	}

}
